package com.carl.guli.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

public class HttpUtil {

    public static Logger log = Logger.getLogger(HttpUtil.class);

    public static String httpPost(String posturl, String params) {

        try {
            URL postUrl = new URL(posturl);
            HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

            connection.setDoOutput(true);

            connection.setDoInput(true);

            connection.setRequestMethod("POST");

            connection.setUseCaches(false);

            connection.setInstanceFollowRedirects(true);

            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.connect();
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());

            out.writeBytes(params);
            out.flush();
            out.close(); // flush and close
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码
            String line = "";
            StringBuffer resultStr = new StringBuffer("");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                resultStr.append(line);
            }

            reader.close();
            connection.disconnect();
            return resultStr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[httpPost] exception" + e.toString());
        }
        return null;
    }

    public static String httpPost2(String posturl, String params) {

        try {
            URL postUrl = new URL(posturl);
            HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

            connection.setDoOutput(true);

            connection.setDoInput(true);

            connection.setRequestMethod("POST");

            connection.setUseCaches(false);

            connection.setInstanceFollowRedirects(true);

            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.connect();
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());

            out.write(params.getBytes("UTF-8"));
            out.flush();
            out.close(); // flush and close
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码
            String line = "";
            StringBuffer resultStr = new StringBuffer("");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                resultStr.append(line);
            }

            reader.close();
            connection.disconnect();
            return resultStr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[httpPost] exception" + e.toString());
        }
        return null;
    }

    public static JSONObject doPost(String url, JSONObject json) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");// 发送json数据需要设置contentType
            post.setEntity(s);


            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static String httpGet(String url) {
        // get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            // 发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** 读取服务器返回过来的json字符串数据 **/
                String strResult = EntityUtils.toString(response.getEntity());
                /** 把json字符串转换成json对象 **/
                jsonResult = JSONObject.parseObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                log.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            log.error("get请求提交失败:" + url, e);
        }
        return jsonResult.toString();
    }

    public static String readData(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            StringBuilder result = new StringBuilder();
            br = request.getReader();
            for (String line = null; (line = br.readLine()) != null; ) {
                result.append(line).append("\n");
            }

            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null)
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }


    public static void main(String[] args) {
        try {
//            String params = "{\"appKey\":\"yitongjin\",\"appSecret\":\"e10adc3949ba59abbe56e057f20f883e\",\"status\":1,\"taskId\":\"10002\",\"taskPassword\":\"3er42ki5\",\"userId\":\"13685\",\"attrList\":[{\"attrId\":1496,\"attrValue\":\"2001001\"},{\"attrId\":\"1530\",\"attrValue\":\"500\"},{\"attrId\":40,\"attrValue\":\""
//                    + URLEncoder.encode("如果是发挥死", "UTF-8")
//                    + "\"},{\"attrId\":1491,\"attrValue\":\"200\"}],\"incentiveList\":[{\"incentiveValue\":\"2\",\"incentivesTypeCd\":2}]}";
//
//            String paramsaString = "inParam=" + params;
//            String returnString = HttpUtil.httpPost("http://61.160.128.34:8000/wa_pa/gate/userTaskSubmit.do",
//                    paramsaString);
//            System.out.print(returnString);

//            String uril = "59元";
//            System.out.println(uril.substring(0,2));
//            System.out.println(RandomStringUtils.randomAscii(20));
//            String md5String = MD5Util.getMD5String("OW]kzv!SLTpaiThvpQ");
//
//            System.out.println(md5String);
//            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx87deb9aeb7228f6a&secret=6a297ccffddffcb73318466c4d698b99";
//            String s = HttpUtil.httpGet(url);
//            System.out.println(s);

            String url2 = "https://api.weixin.qq.com/bizwifi/shop/list?access_token=cvNI3IDMKnZd1DwLEqfXFo9K451HokETJdqsG9dCx2zYXyq50jCn2_KPTGGVFKbxBRz66RIM_MmfSlWxrk6rV1mGHClLQ7zGm72Y97ZYO_IDL5xg3FP3S13fAoPkM9hNJNAhADABFS";
            String s1 = httpPost(url2, "pageindex=1&pagesize=1");
            System.out.println(s1);


        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    public static boolean isRequestFromWexin(String userAgent) {
        if (userAgent == null){
            return false;
        }
        String ua = userAgent.toLowerCase();
        if (ua.indexOf("micromessenger") > 0) {
            return true;
        } else {
            return false;
        }
    }




}
